<template>
	<view class="wrap">
		<view class="u-flex u-row-center">
			<u-avatar :src="pic" size="100"></u-avatar>
		</view>
		<view class="u-flex u-row-center">
			<view>
				<u-upload
						:fileList="avatarFileList"
						@afterRead="afterRead"
						@delete="deletePic"
						name="avatar"
						multiple
						:maxCount="1">
					<u-icon name="camera" size="50"></u-icon>
				</u-upload>
			</view>
		</view>
	</view>
</template>

<script>
	import { uploadAvatar } from '@/api/sr/user'
	export default {
		data() {
			return {
				disabled:false,
				avatarFileList: [],
				header: {
					Authorization: ''
				},
				action: '',
				pic: ''
			}
		},
		onLoad() {
			this.pic = this.$store.state.user.user.avatar;
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`${event.name}FileList`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`${event.name}FileList`].length
				lists.map((item) => {
					this[`${event.name}FileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`${event.name}FileList`][fileListLen]
					this[`${event.name}FileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let data = {name: 'avatarfile', filePath: url}
					uploadAvatar(data).then(response => {
						this.$store.commit('SET_AVATAR', response.data.imgUrl)
						this.pic = response.data.imgUrl
						resolve(response.data.imgUrl)
						uni.showToast({ title: "修改成功", icon: 'success' })
						uni.navigateBack()
					}).catch(errors => {
						reject(errors)
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}
	.wrap {
		.u-flex {
			display: flex;
			flex-direction: row;
			align-items: center;
		}
		.u-row-center {
			justify-content: center;
		}
	}
</style>
